from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from web.models import Project, Bug
from django.db.models import Count, F
from datetime import datetime, timedelta


def index(request):
    return render(request, 'index.html')


@login_required
def dashboard(request):
    # 获取用户参与的项目
    projects = Project.objects.filter(projectuser__user=request.user)

    # 为每个项目计算已解决的bug数量
    for project in projects:
        project.resolved_bug_count = project.bug_set.filter(status__name='已解决').count()

    # 计算关键指标
    total_bugs = Bug.objects.filter(project__in=projects).count()
    resolved_bugs = Bug.objects.filter(project__in=projects, status__name='已解决').count()
    resolved_rate = resolved_bugs / total_bugs if total_bugs > 0 else 0

    # 最近7天创建的BUG
    seven_days_ago = datetime.now() - timedelta(days=7)
    recent_bugs = Bug.objects.filter(project__in=projects, create_datetime__gte=seven_days_ago)\
                        .extra({'date': "date(create_datetime)"})\
                        .values('date')\
                        .annotate(count=Count('id'))\
                        .order_by('date')

    # 按状态分组的BUG
    bugs_by_status = Bug.objects.filter(project__in=projects)\
                                 .values('status__name')\
                                 .annotate(count=Count('id'))

    context = {
        'projects': projects,
        'total_bugs': total_bugs,
        'resolved_bugs': resolved_bugs,
        'resolved_rate': resolved_rate,
        'recent_bugs': recent_bugs,
        'bugs_by_status': bugs_by_status,
    }
    return render(request, 'dashboard.html', context)